# -*- coding: utf-8 -*-
import xbmc,urllib,urllib2,re,xbmcplugin,xbmcgui,os,string,types,time
from    base64      import b64encode
from    types       import *
import core

###################################################################################
##
##      Azureus - Azureus Controls
##      -------------------------------------
##      0.1  - First version with only basic Navigation and functions
###################################################################################
##      Todo:
##      - Error Checking
##      - Extended Labels Info
##      - Text Search
##      - TV Show Search
###################################################################################

## Used to Fudge Params when displaying files.
FUDGER = False

## Azureus XML Strings
Az_Xml                 =   {}
Az_Xml['Begin']        =   '\n\r<REQUEST>'
Az_Xml['End']          =   '\n\r</REQUEST>'
Az_Xml['Method']       =   '\n\r\t<METHOD>%s</METHOD>'
Az_Xml['Request']      =   '\n\r\t<REQUEST_ID>%s</REQUEST_ID>'
Az_Xml['Connect']      =   '\n\r\t<CONNECTION_ID>%s</CONNECTION_ID>'
Az_Xml['Object']       =   '\n\r\t<OBJECT>\n\r\t\t<_object_id>%s</_object_id>\n\r\t</OBJECT>'
Az_Xml['Params_Begin'] =   '\n\r\t<PARAMS>'
Az_Xml['Params']       =   '\n\r\t\t<ENTRY>%s</ENTRY>'
Az_Xml['ParamsExtra']  =   '\n\r\t\t<ENTRY index="0">%s</ENTRY>'
Az_Xml['Params_End']   =   '\n\r\t</PARAMS>'


## Variables
Comms = {}
IP    = ''
PORT  = ''
USER  = ''
PASS  = ''
URL   = ''

## Variable Set Refresh or No Refresh
DirRefresh = False

## XbmcGui Dialog Menu
xDialog = xbmcgui.Dialog()

## DEFAULTPATH
MyPath  = os.getcwd()
MyMedia = MyPath +'\\media'
MyTorrents = "special://profile/torrents/"
if not os.path.exists(MyTorrents):
        os.mkdir(MyTorrents)

def UpdateFileList():
        global TorrentSet
        TorrentSet = os.listdir(MyTorrents)

def UpdateSettings():
        print '--UpdateSettings--'
        global IP,PORT,USER,PASS,URL
        IP      =   xbmcplugin.getSetting("ip")
        PORT    =   xbmcplugin.getSetting("port") 
        USER    =   xbmcplugin.getSetting("username") 
        PASS    =   xbmcplugin.getSetting("password")
        URL     =   'http://' + str(IP) +':'+ str(PORT) + '/process.cgi'


def ClearFiles():
        global TorrentSet
        print '--ClearFiles--'
        for i in TorrentSet:
                os.remove(str(xbmc.translatePath(MyTorrents + str(i))))
        UpdateFileList()
        
        
###################
## COMMUNICATION ##
###################

def HttpCmd(urldta,postdta=''):
        print '--HttpCmd--'
        ## Standard code
        if USER != "None" or PASS != "None" :   header  = {'Authorization':'Basic '+ str(b64encode(USER+":"+PASS))}
        else                                :   header  = {}
        if postdta == ''                    :   postdta = None
        req = urllib2.Request(urldta,postdta,headers=header)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        return link


def XmlHttp(Object='',Method='',Params='',ExtraO='NO') :
    global Comms
    print '--XmlHttp--'
    XMLString   =   ''
    XMLString   +=  Az_Xml['Begin']
    if Object   !=  ''  :   XMLString   +=  str(Az_Xml['Object']   % Object)
    XMLString   +=  str(Az_Xml['Method']   % Method)
    if  (type(Params) == TupleType  and len(Params) >  0 ) or \
        (type(Params) == StringType and Params      != '')  :
        XMLString   +=  str(Az_Xml['Params_Begin'])
        if type(Params) == TupleType :
            for Pp in Params    :   XMLString   +=  str(Az_Xml['Params']  % Pp) 
        else :
            if  ExtraO  ==  'NO'  :
                ## Standard Call and display for Parameters..
                XMLString   +=  str(Az_Xml['Params']       % Params)
            else                                    :
                ## Extra Params used as the Object-Id. This is only used for the addDownload[Torrent]
                ## method as we need to input the object-id of the Torrent.
                AddObj      =   str(Az_Xml['Object']       % Params)           
                XMLString   +=  str(Az_Xml['ParamsExtra']  % AddObj)                       
        XMLString   +=  str(Az_Xml['Params_End'])
    if Comms.has_key('Connect')    :
        XMLString   +=  str(Az_Xml['Connect']   % Comms['Connect'])
    XMLString   +=  str(Az_Xml['Request']   % Comms['Request'])
    XMLString   +=  Az_Xml['End']
    Comms['Request']   +=  1
    print XMLString
    Answer = HttpCmd(URL,XMLString)
    return Answer


def CheckResponse(data):
    print '--CheckResponse--'
    if re.search('</RESPONSE>',data) or re.search('<RESPONSE />',data)  :
        return True
    else                                                                :
        return False

def ClearVars():
    global Comms
    Comms                  =   {}

def CheckComms():
    print '--CheckComms--'
    global Comms
    if (not Comms.has_key('Root')) or \
    (not Comms.has_key('Connect'))  :
        if ( InitConnection() )     :
            return True
        else                        :
            return False
    else                            :
        return True


def InitConnection():
    print '--InitConnection--'
    global Comms
    ## Initialise Connection.
    ClearVars()
    Comms['Request']   =   int(time.time())
    Response           =   XmlHttp('','getSingleton')
    print '-Response-Init Connection'
    print str(Response)
    if Response ==  None    :   raise Exception
    Comms['Root']      =   core.ATag('_object_id',Response)
    Comms['Connect']   =   core.ATag('_connection_id',Response)
    return True


def TorrentMgr()    :
    print '--TorrentMgr--'
    global Comms
    ## Get TorrentManager from Root Object Id.
    if ( DownloadMgr() )   :
        if (not Comms.has_key('TorrentManager'))    :
            Response                        =   XmlHttp(Comms['Root'],'getTorrentManager')
            print '-Response-TorrentMgr'
            print str(Response)
            if Response ==  None            :   raise Exception
            Comms['TorrentManager']    =   core.ATag('_object_id',Response)
    else                        :
        return False
    return True


def DownloadMgr(): 
    print '--DownloadMgr--'
    global Comms
    ## Get Download Manager from Root Object Id.
    if ( CheckComms() )    :
        if (not Comms.has_key('DlManager'))    :
            Response                    =   XmlHttp(Comms['Root'],'getDownloadManager')
            print '-Response-DownloadMgr'
            if Response ==  None        :   raise Exception
            Comms['DlManager']     =   core.ATag('_object_id',Response)
    else                                :
        return False
    return True


def GetConfig():
    print '--GetConfig--'
    global Comms
    ## Get Plugin Config from Root Object Id.
    if ( CheckComms() )    :
        Response                =   XmlHttp(Comms['Root'],'getPluginconfig')
        print '-Response-GetConfig'
        if Response ==  None    :   raise Exception
        Comms['Config']         =   core.ATag('_object_id',Response)
        Exp                     =   re.compile('<ENTRY.*?>(.*?)</ENTRY>',re.DOTALL)
        Dta                     =   re.findall(Exp,Response)
        Comms['CfgData']        =   {}
        Size                    =   len(Dta) / 2
        for Chunk in range(Size):
            Comms['CfgData'][Dta[Chunk]] = str(Dta[Chunk+10])
    else                        :
        return False
    return True


def TorrentOptions(params):
        ## Info Fields ## '0-One','1-Name','2-Id','3-Peers','4-Seeds','5-Complete','6-ForceStart','7-Paused','8-Position','9-Available','10-CompPct',
        ## Info Fields ## '11-DownSpeed','12-Downloaded','13-Elapsed','14-Eta','15-Health','16-Ratio','17-State','18-Tracker','19-UpSpeed','20-Uploaded'
        ## Info Fields ## '21-Queue Length'
        P_Data  = string.split(params,'|')
        Options = []

        Options.append(['Display Files','',''])        
        if P_Data[17] != 'Stopped'              : Options.append(['Stop Torrent','stop',''])
        else                                    : Options.append(['Restart Torrent','restart',''])
        if int(P_Data[8]) > 1                   : Options.append(['Move Torrent Up','moveUp',''])
        if int(P_Data[8]) < int(P_Data[21])     : Options.append(['Move Torrent Down','moveDown',''])
        if int(P_Data[8]) > 1                   : Options.append(['Move Torrent to Top','moveTo[int]','1'])
        if int(P_Data[8]) < int(P_Data[21])     : Options.append(['Move Torrent to Bottom','moveTo[int]',str(P_Data[21])])
        if P_Data[6] == 'True'                  : Options.append(['ForceStart - Disable','setForceStart[boolean]','false'])
        else                                    : Options.append(['ForceStart - Enable','setForceStart[boolean]','true'])
        Options.append(['Remove Torrent','remove',''])
        Options.append(['Remove Torrent - Delete file' ,'remove[boolean,boolean]',('true','false')])
        Options.append(['Remove Torrent - Delete file+data','remove[boolean,boolean]',('true','true')])

        ## Display Menu:
        MenuList = []
        for List in Options     :
                MenuList.append(List[0])
        Answer = xDialog.select('Action Torrent',MenuList)

        ## Process the answer..
        if Answer != -1 :
                if Options[Answer][0] == 'Display Files':
                        GetFiles(str(P_Data[2]))
                else:
                        DownloadMgr()
                        Response = XmlHttp(P_Data[2],Options[Answer][1],Options[Answer][2])

def Extras():
        global Comms
        Options = []
        Options.append(['Refresh','',''])
        Options.append(['Resume - All Downloads','resumeDownloads',''])
        Options.append(['Pause - All Downloads','pauseDownloads',''])
        Options.append(['Stop - All Downloads','stopAllDownloads',''])
        Options.append(['Start - All Downloads','startAllDownloads',''])
        Options.append(['Azureus Configuration','',''])
        ## Display Menu:
        MenuList    =   []
        for List in Options     :
                MenuList.append(List[0])
        Answer = xDialog.select('Menu Options',MenuList)
        if Answer != -1         :
                if      MenuList[Answer] == 'Azureus Configuration'     : 
                        AZConfig()
                elif    'Downloads' in MenuList[Answer]                 :                                
                        DownloadMgr()
                        Object = Comms['DlManager']
                        Response = XmlHttp(Object,Options[Answer][1],Options[Answer][2])


def AZConfig():
        ## Core Parameter configuration Options.
        global Comms
        if (GetConfig()) :
                print Comms['CfgData']
                Options = []
                for key in Comms['CfgData']:
                        Options.append([str(key) +': ['+ str(Comms['CfgData'][key]) +']','setIntParameter[String,int]',''])

                Options.append(['Finish','',''])
                ## Display Menu:
                MenuList    =   []
                for List in Options     :
                        MenuList.append(List[0])
                Answer = xDialog.select('Azureus Config',MenuList)
                if Answer != -1         :
                    ## Core parameter change requested.
                    if Options[Answer][0] != 'Finish':
                            Method  =   Options[Answer][1]
                            Param1  =   string.split(MenuList[Answer],':')[0]
                            Param2  =   xDialog.numeric(0,str(Param1) +': ['+ str(Comms['CfgData'][Param1]) +']')
                            if Param2 != -1 :
                                ## Parameter OK.
                                Response = XmlHttp(str(Comms['Config']),Method,(str(Param1),str(Param2)))



## MAIN CODE FUNCTIONS ##      
def GetTorrents(wanted,Extras): #WORKING
    print '--GetTorrents--'
    global Comms
    ## Initialise Variables that will be passed back ##
    Tor                     =   {}
    Tor_Array               =   []
    Queue                   =   0
    GlobalMsg               =   ''

    if wanted == 'false':       Mode = 1
    else                :       Mode = 2
    
    ## Now Retrieve the list of Torrents from Azureus ##
    if ( DownloadMgr() )   :
        Response                =   XmlHttp(Comms['DlManager'],'getDownloads')
        if Response ==  None    :   raise Exception

        ## Setup some temp Variables ##            
        _tmp                    =   []
        sp1                     =   0
        sp2                     =   0

        ## Compile options ##
        Filter                  =   re.compile(
                                      '<ENTRY index=\"(.*?)\">.*?'                      ##Entry     -   0
                                      '<_object_id>(.*?)</_object_id>.*?'               ##Id        -   1
                                      '<announce_result>.*?' 
                                      '<non_seed_count>(.*?)</non_seed_count>.*?'       ##nonseed   -   2
                                      '<seed_count>(.*?)</seed_count>.*?'               ##seed      -   3
                                      '<complete>(.*?)</complete>.*?'                   ##complete  -   4
                                      '<force_start>(.*?)</force_start>.*?'             ##force     -   5
                                      '<name>(.*?)</name>.*?'                           ##name      -   6
                                      '<paused>(.*?)</paused>.*?'                       ##paused    -   7
                                      '<position>(.*?)</position>.*?'                   ##position  -   8
                                      '<scrape_result>.*?'
                                      '<non_seed_count>(.*?)</non_seed_count>.*?'       ##nonseed   -   9
                                      '<seed_count>(.*?)</seed_count>.*?'               ##seed      -   10
                                      '<stats>.*?'
                                      '<availability>(.*?)</availability>.*?'           ##avail     -   11
                                      '<completed>(.*?)</completed>.*?'                 ##completed -   12
                                      '<download_average>(.*?)</download_average>.*?'   ##downavg   -   13
                                      '<downloaded>(.*?)</downloaded>.*?'               ##download  -   14
                                      '<elapsed_time>(.*?)</elapsed_time>.*?'           ##elapsed   -   15
                                      '<eta>(.*?)</eta>.*?'                             ##eta       -   16
                                      '<health>(.*?)</health>.*?'                       ##health    -   17
                                      '<share_ratio>(.*?)</share_ratio>.*?'             ##ratio     -   18
                                      '<status>(.*?)</status>.*?'                       ##status    -   19
                                      '<tracker_status>(.*?)</tracker_status>.*?'       ##tkrstat   -   20
                                      '<upload_average>(.*?)</upload_average>.*?'       ##uploadavg -   21
                                      '<uploaded>(.*?)</uploaded>'                      ##uploaded  -   22
                                      ,re.DOTALL)

        _data                   =   re.findall(Filter,Response)

        ## Now loop through all the Data filtered and build a Dictionary from it.
        for _a in _data :
                sp1 += int(_a[13])
                sp2 += int(_a[21])
                if _a[4] == wanted:
                        Nm                      =   str(_a[6])
                        Tor[Nm]                 =   {}
                        Tor[Nm]['Id']           =   str(_a[1])
                        Tor[Nm]['Peers']        =   str(_a[2])        +'('+ str(_a[9])          +')'
                        Tor[Nm]['Seeds']        =   str(_a[3])        +'('+ str(_a[10])         +')'
                        Tor[Nm]['Complete']     =   str(_a[4]).capitalize()
                        Tor[Nm]['ForceStart']   =   str(_a[5]).capitalize()
                        Tor[Nm]['Paused']       =   str(_a[7]).capitalize()
                        Tor[Nm]['Position']     =   int(_a[8])
                        Tor[Nm]['Available']    =   str(_a[11][:-3])
                        Tmp                     =   str(_a[12].rjust(4,'0'))
                        Tor[Nm]['CompPct']      =   (Tmp[:3] +'.'+ Tmp[-1:] +'%').strip('0')
                        Tor[Nm]['DownSpeed']    =   str(_a[13])[:-3]  +'.'+ str(_a[13])[-3:]    +' kBs'
                        Tor[Nm]['Downloaded']   =   str(int(_a[14]) / 1024)[:-3]                +' MB'
                        Tor[Nm]['Elapsed']      =   str(_a[15])
                        Tor[Nm]['Eta']          =   str(_a[16])
                        Tor[Nm]['Health']       =   str(_a[17])
                        Tmp                     =   str(_a[18].rjust(4,'0'))
                        Tor[Nm]['Ratio']        =   (Tmp[:1] +'.'+ Tmp[-3:] +'%').strip('0')
                        Tor[Nm]['State']        =   str(_a[19])
                        Tor[Nm]['Tracker']      =   str(_a[20])
                        Tor[Nm]['UpSpeed']      =   str(_a[21])[:-3]  +'.'+ str(_a[21])[-3:]    +' kBs'
                        Tor[Nm]['Uploaded']     =   str(int(_a[22]) / 1024)[:-3]                +' MB'
                        Queue                   +=  1
                        _tmp.append([int(_a[8]),Nm])
        _tmp.sort()

        if (GetConfig()) :
            GlobalMsg = '>> Downloads: '                                                    + \
                        str(sp1)[:-3].rjust(1,'0') + '.'                                   + \
                        str(sp1)[-3:-2].rjust(1,'0')                                       + \
                        ' kB/s'                                                            + \
                        ' - Max: ['+ str(Comms['CfgData']['Max Download Speed KBs']) +'K] <<'+ \
                        '    >> Uploads: '                                               + \
                        str(sp2)[:-3].rjust(1,'0') + '.'                                   + \
                        str(sp2)[-3:-2].rjust(1,'0')                                       + \
                        ' kB/s'                                                            + \
                        ' - Max: ['+ str(Comms['CfgData']['Max Upload Speed KBs'])   +'K] <<'        
            if wanted == 'true':
                    XImage = MyMedia +'\\Upload.png'
                    Setup  = 'Upload'
            else:
                    XImage = MyMedia +'\\Download.png'
                    Setup  = 'Download'
            addDir(GlobalMsg, '' ,Setup + '-Options',1000, XImage)

        ## Create the Listem that will be displayed..
        for Item in _tmp:
            Image = MyMedia + '\\'+ 'Health-'+ str(Tor[Item[1]]['Health']) +'.png'

            if Tor[Item[1]]['Complete'] == 'False':
                    Speed = 'Down: '+ Tor[Item[1]]['DownSpeed']
                    Pct   = '%: ' + Tor[Item[1]]['CompPct']
            else                            :
                    Speed = 'Up:'+ Tor[Item[1]]['UpSpeed']
                    Pct   = '%: ' + Tor[Item[1]]['Ratio']

            Label1 = '['+ str(Item[0]) +'] '+ str(Item[1]) + ' - '+ str(Pct) +' - '+ str(Speed) +' - Seeds: '+ Tor[Item[1]]['Seeds']
            Url    = str(Item[0]) +'|'+ str(Item[1])    +'|'+ str(Tor[Item[1]]['Id'])           +'|'+ \
                     str(Tor[Item[1]]['Peers'])         +'|'+ str(Tor[Item[1]]['Seeds'])        +'|'+ \
                     str(Tor[Item[1]]['Complete'])      +'|'+ str(Tor[Item[1]]['ForceStart'])   +'|'+ \
                     str(Tor[Item[1]]['Paused'])        +'|'+ str(Tor[Item[1]]['Position'])     +'|'+ \
                     str(Tor[Item[1]]['Available'])     +'|'+ str(Tor[Item[1]]['CompPct'])      +'|'+ \
                     str(Tor[Item[1]]['DownSpeed'])     +'|'+ str(Tor[Item[1]]['Downloaded'])   +'|'+ \
                     str(Tor[Item[1]]['Elapsed'])       +'|'+ str(Tor[Item[1]]['Eta'])          +'|'+ \
                     str(Tor[Item[1]]['Health'])        +'|'+ str(Tor[Item[1]]['Ratio'])        +'|'+ \
                     str(Tor[Item[1]]['State'])         +'|'+ str(Tor[Item[1]]['Tracker'])      +'|'+ \
                     str(Tor[Item[1]]['UpSpeed'])       +'|'+ str(Tor[Item[1]]['Uploaded'])     +'|'+ \
                     str(len(_tmp))
            addDir(Label1, '',Url,Mode, Image)


## Display Files fr the selected Torrent ##
            
def GetFiles(FILEHASH) :
    ## Initialise Temp Variables
    print '--GetFiles--'
    global Comms,mode,name,url,FUDGER

    Tor                     =   {}
    Tor_Array               =   []
    GlobalMsg               =   ''

    if ( DownloadMgr() )   :
            if not Comms.has_key('DiskManager') :
                Response    =   XmlHttp(FILEHASH,'getDiskManager')
                if Response ==  None    :   raise Exception
                Exp         =   re.compile('<_object_id>(.*?)</_object_id>',re.DOTALL)
                Obj         =   re.findall(Exp,Response)
                if len(Obj) ==  1   :   Comms['DiskManager']   =   str(Obj[0][0])
                else                :   Comms['DiskManager']   =   'Must Have Been Running'
                
            if Comms.has_key('DiskManager') or re.search('RESPONSE',Response) :
                ## Data is Ok Continue
                Response    =   XmlHttp(FILEHASH,'getDiskManagerFileInfo')
                if Response ==  None    :   raise Exception
                Exp         =   re.compile('<ENTRY index=\"(\d+)\">.*?'
                                          '<_object_id>(.*?)</_object_id>.*?'
                                          '<downloaded>(.*?)</downloaded>.*?'
                                          '<file>(.*?)</file>.*?'
                                          '<is_priority>(.*?)</is_priority>.*?'
                                          '<is_skipped>(.*?)</is_skipped>.*?'
                                          '<length>(\d+)</length>.*?'
                                          '</ENTRY>',re.DOTALL)
                Tar = re.findall(Exp,Response)

                ## Pass through List to get allfiles in a variable
                AllFiles = ''
                if len(Tar) > 0:
                        for No in range(len(Tar))   :
                                AllFiles = AllFiles + str(Tar[No][1])+'|'

                ## NOW WE NEED TO FUDGE THE SYSTEM
                FUDGER = True

                if len(Tar) > 0  :
                    ## We Have Data...
                    addDir('Torrent File Listing', '',FILEHASH,5, MyMedia +'\\folder.png')
                    for No in range(len(Tar))   :
                        Nm                  =   str(os.path.basename(Tar[No][3]))
                        Tor[Nm]             =   {}
                        Tor[Nm]['Idx']      =   str(Tar[No][1])
                        Tor[Nm]['Done']     =   str(Tar[No][2])
                        Tor[Nm]['Pri']      =   str(Tar[No][4])
                        Tor[Nm]['Skip']     =   str(Tar[No][5])
                        Tor[Nm]['Size']     =   NiceSize(int(Tar[No][6]))
                        if   Tor[Nm]['Pri'] == 'false' and Tor[Nm]['Skip'] == 'false'   :   Health = 4
                        elif Tor[Nm]['Pri'] == 'true'  and Tor[Nm]['Skip'] == 'false'   :   Health = 2
                        elif Tor[Nm]['Pri'] == 'False' and Tor[Nm]['Skip'] == 'true'    :   Health = 5
                        else                                                            :   Health = 1
                        Tor[Nm]['Health']   =   str(Health)
                        Image               =   MyMedia +'\\Health-'+ str(Health) +'.png'
                        Val1                =   int(Tor[Nm]['Done'])
                        Val2                =   int(Tar[No][6])
                        PctX                =   int((Val1*100)/Val2)
                        Label1              =   str(Nm) + ' - [ Size:' + str(Tor[Nm]['Size'])  +' ] - [ Done: '+ str(PctX) + '% ]'
                        Url                 =   FILEHASH +'|'+ Tor[Nm]['Idx'] + '|' + AllFiles
                        addDir(Label1, '',Url,5, Image)


def NiceSize(Size) :
    Loops   =   0
    Arr     =   [' BYTES',' KB',' MB',' GB',' TB']
    while Size > 1024 :
        Size    =   Size / 1024
        Loops   =   Loops + 1
    return str(Size) + str(Arr[Loops])


def FileMenu(TorrentObj,SingleFile,AllFiles):
    print '--FileMenu--'
    Object          =   SingleFile
    Options         =   ['Do Not Download','Set Priority Normal','Set Priority High']
    Answer          =   xDialog.select('Perform File Action',Options)
    print 'Answer=='+str(Answer)
    if Answer != -1         :
        Methods             =   []
        if      Answer  ==  0   :
            Methods.append(['setSkipped[boolean]','true'])
        elif    Answer  ==  1   :
            Methods.append(['setSkipped[boolean]','false'])
            Methods.append(['setPriority[boolean]','false'])
        elif    Answer  ==  2   :
            Methods.append(['setSkipped[boolean]','false'])
            Methods.append(['setPriority[boolean]','true'])
            
        if ( DownloadMgr() )   :
                print '***CHECK 1**'
                Response    =   XmlHttp(TorrentObj,'getDiskManager')
                print '***Methods***'
                print Methods
                for Item in Methods :
                    print '***CHECK 2**'
                    Response    =   XmlHttp(str(Object),str(Item[0]),str(Item[1]))


## ADD TORRENTS ##    

def SendTorrent(TorrentFile):
    print '--SendTorrent--'
    global Comms
    ## Start Torrent Manager..
    if ( TorrentMgr() )    :

        ## Open File and create Hex String from it..
        f           =   open(MyTorrents + TorrentFile,"rb")
        data        =   f.read()
        f.close()
        HexStr      =   ''
        for i in range(len(data)):
            HexStr += str("%02X " % ord(data[i:i+1])).strip()

        ## Now create the Torrent from the Hex string..
        Object      =   Comms['TorrentManager']
        Method      =   'createFromBEncodedData[byte[]]'
        Response    =   XmlHttp(Object,Method,HexStr)
        if Response ==  None    :   raise Exception
        else                    :   TorrentObj  =   core.ATag('_object_id',Response)

        ## Now Add the Torrent..
        Method      =   'addDownload[Torrent]'
        Response    =   XmlHttp(Comms['DlManager'],Method,str(TorrentObj),ExtraO='YES')
        if Response ==  None    :
                return False
        else                    :
                os.remove(str(xbmc.translatePath(MyTorrents + TorrentFile)))
                return True
    else                        :
        return False


###################################################################################
UpdateSettings()
        
def DEFAULT():
        print '--DEFAULT--'
        addDir('Downloads', '' ,'',10, MyMedia + '\\Download.png')
        addDir('Uploads', '' ,'',20, MyMedia + '\\Upload.png')
        addDir('Azureus Configuration', '' ,'',30, MyMedia + '\\Plugin.png')
        AllTorrents = len(TorrentSet)
        addDir('Add Torrents','','',99,MyMedia +'\\Add.png')

def LISTTORRENTS():
        print '--LISTTORRENTS--'
        addDir('Upload All', '' ,'',100, MyMedia + '\\Upload.png')
        addDir('Delete All', '' ,'',102, MyMedia + '\\Delete.png')
        for i in TorrentSet:
                addDir(i, '' ,'',101, MyMedia + '\\Upload.png')               
        
def NiceName(fName):
        print '--NiceName--'
        NewName     =   ''
        tName       =   fName.rsplit('.',1)
        xName       =   tName[0][:30]
        if ( xName[0].isdigit() )   :
                xName = 'x'+ str(xName)
        for xChar in xName                  :
                if      xChar.isalnum()         :   NewName  += str(xChar)
                elif    xChar.isspace()         :   NewName  += '_'
                else                            :   pass
        if len(NewName) > 4                 :
                return NewName +'.torrent'
        else                                :
                return None

def get_params():
        print '--get_params--'
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param



def addDir(name,label, url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, label, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

        
## Get list of Torrent Files
UpdateFileList()

## Check if first run if so run Plugin Config.
FlagFile = MyPath + '\\flagfile.flg'
if not os.path.isfile(FlagFile):
        PluginConfig()
        ## Save The file
        f   =   open(str(FlagFile),'wb')
        f.write('dummy')
        f.close()
              

params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)

if name == None:       ## Default
        DEFAULT()

elif name == 'Downloads' :
        print 'Downloads--'
        GetTorrents('false','')

elif name == 'Uploads':
        print 'Uploads--'
        GetTorrents('true','')

elif name == 'Azureus Configuration':
        print 'Azureus Settings--'
        AZConfig()
        DEFAULT()
        DirRefresh = True

elif name == 'Download-Options':
        print 'Download-Options--'
        GetTorrents('false','')
        DirRefresh = True

elif name == 'Upload-Options':
        print 'Upload-Options--'
        GetTorrents('true','')
        DirRefresh = True

elif name == 'Torrent File Listing':
        print 'Torrent File Listing'
        GetFiles(url)
        DirRefresh = True
        

elif mode==1:
        print 'TorrentOptions--Download'
        TorrentOptions(url)
        if FUDGER != True:
                GetTorrents('false','')
                DirRefresh = True

elif mode==2:
        print 'TorrentOptions--Upload'
        TorrentOptions(url)
        if FUDGER != True:
                GetTorrents('true','')
                DirRefresh = True
        
elif mode==5:                                     ## Files
        print 'Files--'
        TorrentObj = string.split(url,'|')[0]
        SingleFile = string.split(url,'|')[1]
        AllFiles   = string.split(url,'|')
        FileMenu(TorrentObj,SingleFile,AllFiles)
        GetFiles(TorrentObj)
        DirRefresh = True

elif mode==99:                                    ## Add Torrents Menu
        print 'Torrents--'
        LISTTORRENTS()
        UpdateFileList()
                
elif mode==100:                                    ## Add - All Torrents
        print 'Add All--'
        for i in TorrentSet:
                Result = SendTorrent(str(i))
        UpdateFileList()
        LISTTORRENTS()
        DirRefresh = True
        
elif mode==101:                                    ## Add Single Torrent
        print 'Add -' + str(name)
        Result = SendTorrent(str(name))
        UpdateFileList()
        LISTTORRENTS()
        DirRefresh = True
        
elif mode==102:                                    ## Delete All Torrents
        print 'Delete All -'
        ClearFiles()
        LISTTORRENTS()
        DirRefresh = True

elif mode==1000 and url == 'Download-Options':    ##  Download - Extras
        print 'Download - Extras'
        Extras()
        GetTorrents('false','')
        DirRefresh = True
        
elif mode==1000 and url == 'Upload-Options':      ##  Upload - Extras
        print 'Upload - Extras'
        Extras()
        GetTorrents('true','')
        DirRefresh = True

print'****** REFRESH ******'
print str(sys.argv[1])
print str(DirRefresh)
xbmcplugin.addSortMethod(int(sys.argv[1]), 0)
xbmcplugin.endOfDirectory(int(sys.argv[1]),updateListing=DirRefresh)
